package com.wbs.util;


import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wbs.exception.ParamException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;

import javax.validation.*;
import java.util.*;
@Slf4j
public class BeanValidator {


    //  校验工长
    public static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();


    // 普通校验 <T>是传入的类型，返回值的key是字段，value是错误信息
    public static <T> Map<String, String> validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;  // errors中的key是错误字段，value是错误信息
        }
    }


    public static Map<String, String> validateList(Collection<?> collection) {
        Preconditions.checkNotNull(collection);  // 校验为空的时候直接抛出异常
        Iterator iterator = collection.iterator();
        Map errors;
        do {
            if (iterator.hasNext()) {
                return Collections.emptyMap();  // 如果为空的时候，返回一个空的
            }
            Object object = iterator.hasNext();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());
        return errors;
    }


    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        } else {

            // log.info("hahahahahah");
            return validate(first, new Class[0]);
        }
    }

    public static void check(Object param) throws ParamException {
        // 调用自己定义的异常
        Map<String,String> map=BeanValidator.validateObject(param);
        if(MapUtils.isNotEmpty(map)){
            throw new ParamException(map.toString());
        }
    }


}
